package ee.nutilovi.praktikaportaal.tools;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class VerificationTools {
	
	public static boolean isValidUsername(String username) {
		if (username.matches("^[a-zA-Z0-9_-]{3,20}$")) {
			DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
			Key key = KeyFactory.createKey("User", username);
			try {
				@SuppressWarnings("unused")
				Entity user = ds.get(key);
				return false;
			} catch (EntityNotFoundException e) {
				return true;
			}
		} return false;
	}
	
	public static boolean isValidEmail(String email) {
		if (email.matches("^[!#-'\\*\\+\\-/0-9=\\?A-Z\\^_`a-z{-~]+(\\.[!#-'\\*\\+\\-/0-9=\\?A-Z\\^_`a-z{-~]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) {
			return true;
		} return false;
	}
	
	public static boolean isValidPassword(String password, String verify) {
		if (password.length() > 3 && password.equals(verify)) {
			return true;
		} return false;
	}
	
	public static Entity isCorrectLogin (String username, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Key userKey = KeyFactory.createKey("User", username);
		
		Entity user;		
		try {
			user = ds.get(userKey);
		} catch (EntityNotFoundException e) {
			return null;
		}
		
		String dsString = (String) user.getProperty("password");
		
		boolean isCorrectPassword = isCorrectPassword(password, dsString);
		
		if (isCorrectPassword) {
			return user;
		} else {
			return null;
		}
	}
	
	public static boolean isCorrectPassword (String inputPassword, String dsString) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		String salt = dsString.split("\\|")[1];
		String inputString = CryptoTools.hashPassword(inputPassword, salt);
		
		if (inputString.equals(dsString)) {
			return true;
		} else return false;
	}
}
